﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using Eneta.Portal.Common.Dto;
using Eneta.Portal.Common.Repository;
using Microsoft.SharePoint;
using Eneta.Portal.Common.Definitions;
using Eneta.Portal.Common;

namespace Eneta.Portal.Controls
{
    public class TagsSelectionControl : UserControl
    {
        protected Repeater keywordGroupsRepeater;
        public int ItemId { get; set; }
        
        protected LiteratureDto Item {get; private set;}
   
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            keywordGroupsRepeater.ItemDataBound += new RepeaterItemEventHandler(keywordGroupsRepeater_ItemDataBound);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (ItemId != -1 && ItemId != 0)
            {
                var repository = new LiteratureRepository(SPContext.Current.Web);
                Item = repository.GetLiteratureItemById(ItemId);
            }
            else { return; }
            var currentUser = SPContext.Current.Web.CurrentUser;
            if (currentUser == null || !currentUser.IsSiteAdmin)
                this.Visible = false;

            if (IsPostBack)
                return;

            BindKeywordGroups();

        }

        private void BindKeywordGroups()
        {
            var query = from k in GetAllKeywords()
                        orderby k.GroupName
                        select k.GroupName;
            if (query.Count() > 0)
            {
                keywordGroupsRepeater.DataSource = query.Distinct();
                keywordGroupsRepeater.DataBind();
            }
        }

        void keywordGroupsRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var groupName = (string)e.Item.DataItem;

            var groupNameLabel = (Label)e.Item.FindControl("groupNameLabel");
            groupNameLabel.Text = groupName;

            var keywordCheckList = (CheckBoxList)e.Item.FindControl("KeywordCheckList");

            Logger.LogInfo("TagSelectionControl: before keywords", "keywordsGroupsRepeater");
            var query = from k in GetAllKeywords()
                        where k.GroupName == groupName
                        orderby k.Title
                        select k;
            keywordCheckList.DataSource = query;
            keywordCheckList.DataBind();

            foreach (ListItem item in keywordCheckList.Items)
            {
                var keywordId = int.Parse(item.Value);
                item.Selected = Item.Keywords.Exists(p => p.Id == keywordId);
            }
        }

        private List<KeywordDto> _allKeywords;
        private List<KeywordDto> GetAllKeywords()
        {
            if (_allKeywords != null)
                return _allKeywords;

            var keywords = new List<KeywordDto>();
            var siteId = SPContext.Current.Site.ID;

            var sec = new SPSecurity.CodeToRunElevated(delegate
            {
                using (var site = new SPSite(siteId))
                {
                    using (var web = site.OpenWeb())
                    {
                        Logger.LogInfo(web.Title + "otsime keyworde", "TagsSelectionControl");
                        var list = web.Lists[Lists.Keywords];
                        var items = list.Items;

                        if (items == null)
                            return;
                        if (items.Count < 1)
                            return;

                        Logger.LogInfo("Enne KeywordGroup saamist", "TagsSelectionControl");
                        foreach (SPListItem item in items)
                        {
                            var lookup = new KeywordDto();
                            lookup.Id = item.ID;
                            lookup.Title = item.Title;
                            if (item["KeywordGroup"] != null)
                                lookup.GroupName = item["KeywordGroup"].ToString();
                            keywords.Add(lookup);
                        }
                    }
                }
            });
            SPSecurity.RunWithElevatedPrivileges(sec);

            _allKeywords = keywords;
            return _allKeywords;
        }

        public SPFieldLookupValueCollection GetSelectedKeywords()
        {
            var result = new SPFieldLookupValueCollection();

            foreach (RepeaterItem groupItem in keywordGroupsRepeater.Items)
            {
                CheckBoxList checkList = (CheckBoxList)groupItem.FindControl("KeywordCheckList");
                if (checkList == null)
                {
                    Logger.LogWarning("TagsSelectionControl.GetSelectedKeywords: Cannot find KeywordCheckList", GetType().ToString());
                    continue;
                }
                foreach (ListItem checkItem in checkList.Items)
                {
                    if (!checkItem.Selected)
                        continue;
                    var id = int.Parse(checkItem.Value);
                    var text = checkItem.Text;
                    var keyword = new SPFieldLookupValue(id, text);
                    result.Add(keyword);
                }
            }
            return result;
        }

        public bool SaveŚelectedKeywords(SPListItem item)
        {
            bool successful = false;
            var code = new SPSecurity.CodeToRunElevated(
                delegate
                    {
                        var status = item.ModerationInformation.Status;
                        if (item.File.CheckOutStatus == SPFile.SPCheckOutStatus.None)
                            item.File.CheckOut();
                        var keywords = GetSelectedKeywords();
                        if (keywords.Count != 0)
                        {
                            item["EnetaKeywords"] = keywords;
                            successful = true;
                        }
                        else
                        {
                            item["EnetaKeywords"] = null;
                        }
                        item.SystemUpdate();
                        item.File.CheckIn(string.Empty);
                    });
            SPSecurity.RunWithElevatedPrivileges(code);
            return successful;
        }
    }
}
